const express = require('express');
const { createCanvas } = require('canvas');

const app = express();
const port = 3000;


// Middleware for parsing JSON and urlencoded data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 根目录路由，发送一个HTML页面，其中包含用于显示验证码的图像
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
app.post('/generate-captcha', (req, res) => {
    const text = req.body.text;
    if (!text) {
        return res.status(400).send('No text provided');
    }

    const width = 500;
    const height = 80;
    const canvas = createCanvas(width, height);
    const ctx = canvas.getContext('2d');

    // 绘制背景噪音
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, width, height);
    for (let i = 0; i < width / 4; i++) {
        ctx.fillStyle = randomColor(150, 255);
        ctx.beginPath();
        ctx.arc(randomInt(0, width), randomInt(0, height), randomInt(1, 3), 0, 2 * Math.PI);
        ctx.fill();
    }

    // 添加文字
    const chars = text.split('');
    let offsetX = 10;
    const offsetY = height / 2 + 10;
    chars.forEach(char => {
        const fontSize = randomInt(30, 40);
        ctx.font = `${fontSize}px 宋体`;
        ctx.fillStyle = randomColor(0, 150);
        ctx.save();
        ctx.translate(offsetX, offsetY);
        ctx.rotate(randomInt(-30, 30) * Math.PI / 180);
        ctx.fillText(char, 0, 0);
        ctx.restore();
        offsetX += fontSize;
    });

    // 添加干扰线
    for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = randomColor(0, 255);
        ctx.beginPath();
        ctx.moveTo(randomInt(0, width), randomInt(0, height));
        ctx.lineTo(randomInt(0, width), randomInt(0, height));
        ctx.lineWidth = randomInt(1, 3);
        ctx.stroke();
    }

    // 将图像转换为数据URL
    const dataUrl = canvas.toDataURL();

    // 发送图像数据
    res.send(`<img src="${dataUrl}" />`);
});

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomColor(min, max) {
    const r = randomInt(min, max);
    const g = randomInt(min, max);
    const b = randomInt(min, max);
    return `rgb(${r},${g},${b})`;
}
app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});
